//
//  BVWorkoutDetailViewController.m
//  AFNetworking
//
//  Created by xiute on 2019/10/23.
//

#import "BVWorkoutDetailViewController.h"
#import "BVWorkoutDetailBigPicTableViewCell.h"
#import "BVPersonalBasketballInfoTableViewCell.h"
#import "BVHomeLocationView.h"
#import "BVWorkoutDetailAllVideoTipTableViewCell.h"
#import "BVService.h"
#import "BVVideoPlayView.h"
#import "Masonry.h"
#import "BVWorkOutDetailModel.h"
#import "BVWorkoutDetailNormalTableViewCell.h"

@interface BVWorkoutDetailViewController ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *navTopMargin;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property (nonatomic, strong) BVHomeLocationView *locationView;

@property (nonatomic, strong) NSMutableArray<BVMetaModel *> *dataSource;

@property (nonatomic, strong) BVWorkOutDetailModel *workoutDetailModel;

@end

@implementation BVWorkoutDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadInitData];
    
}

- (void)loadInitData {
    [[BVService shareInstance] get:@"vmeta" param:@{@"workout": self.workoutModel.objectId} complete:^(BOOL success, id  _Nullable response) {
        if (success) {
            [self handleDataWithList:response[@"data"][@"results"]];
        }
    }];
    NSString *url = [NSString stringWithFormat:@"workout/%@", self.workoutModel.objectId];
    [[BVService shareInstance] get:url param:@{} complete:^(BOOL success, id  _Nullable response) {
        if (success) {
            self.workoutDetailModel = [[BVWorkOutDetailModel alloc] initWithDictionary:response[@"data"] error:nil];
            [self.tableview reloadData];
        }
    }];
    
}

- (void)handleDataWithList:(NSArray<NSDictionary *> *)dataList {
    self.dataSource = [BVMetaModel arrayOfModelsFromDictionaries:dataList error:nil];
    [self.tableview reloadData];
}


- (void)setupViews {
    self.navTopMargin.constant = isIPhoneX?44:20;
    [self.backButton setContentEdgeInsets:UIEdgeInsetsMake(11, 11, 11, 11)];
    [self.tableview registerNib:[UINib nibWithNibName:@"BVWorkoutDetailBigPicTableViewCell" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] forCellReuseIdentifier:@"BVWorkoutDetailBigPicTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"BVPersonalBasketballInfoTableViewCell" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] forCellReuseIdentifier:@"BVPersonalBasketballInfoTableViewCell"];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 55)];
    [view addSubview:self.locationView];
    _tableview.tableHeaderView = view;
    [self.tableview registerNib:[UINib nibWithNibName:@"BVWorkoutDetailAllVideoTipTableViewCell" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] forCellReuseIdentifier:@"BVWorkoutDetailAllVideoTipTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"BVWorkoutDetailNormalTableViewCell" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] forCellReuseIdentifier:@"BVWorkoutDetailNormalTableViewCell"];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
}



- (IBAction)backAct:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)playVideoWithIndexPath:(NSIndexPath *)indexPath model:(BVMetaModel *)model isFirst:(BOOL)isfirst {
    BVWorkoutDetailNormalTableViewCell *cell = (BVWorkoutDetailNormalTableViewCell *)[self.tableview cellForRowAtIndexPath:indexPath];
    BVVideoPlayView *view = [BVVideoPlayView sharedInstance];


    UIImageView *imageV = nil;
    if (isfirst) {
        [cell.firstImageView addSubview:view];
        imageV = cell.firstImageView;
    }else {
        [cell.secondImageView addSubview:view];
        imageV = cell.secondImageView;
    }
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(imageV);
    }];
    view.url = [model.video buildUrlString];
    [view.playController prepareToPlay];
    [view.playController play];
}


#pragma mark - gesture delegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return YES;
}

#pragma mark - tableview delegate and datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (self.dataSource.count / 2) + 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        BVPersonalBasketballInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BVPersonalBasketballInfoTableViewCell" forIndexPath:indexPath];
        [cell configWithWorkoutModel:self.workoutDetailModel];
        return cell;
    }
    if (indexPath.row == 1) {
        BVWorkoutDetailBigPicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BVWorkoutDetailBigPicTableViewCell" forIndexPath:indexPath];
        
        return cell;
    }
    if (indexPath.row == 2) {
        BVWorkoutDetailAllVideoTipTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BVWorkoutDetailAllVideoTipTableViewCell" forIndexPath:indexPath];
        
        return cell;
        
    }
    BVWorkoutDetailNormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BVWorkoutDetailNormalTableViewCell" forIndexPath:indexPath];
    BVMetaModel *firstModel = self.dataSource[(indexPath.row - 3)];
    NSMutableArray *dataAray = @[firstModel].mutableCopy;
    BVMetaModel *secondModel = nil;
    if ((indexPath.row - 3) + 1 < self.dataSource.count - 1) {
        secondModel = self.dataSource[(indexPath.row - 3) + 1];
        [dataAray addObject:secondModel];
    }
    [cell configWithModel:dataAray.copy];
    __weak typeof(self)weakSelf = self;
    [cell setFirstBlock:^{
        [weakSelf playVideoWithIndexPath:indexPath model:firstModel isFirst:YES];
    }];
    [cell setSecondBlock:^{
        if ((indexPath.row - 3) + 1 < self.dataSource.count - 1) {
            [weakSelf playVideoWithIndexPath:indexPath model:secondModel isFirst:NO];
        }
    }];
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return [BVPersonalBasketballInfoTableViewCell cellHeight];
    }
    if (indexPath.row == 1) {
        return [BVWorkoutDetailBigPicTableViewCell cellHeight];
    }
    if (indexPath.row == 2) {
        return [BVWorkoutDetailAllVideoTipTableViewCell cellHeight];
    }
    return [BVWorkoutDetailNormalTableViewCell cellHeight];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell isKindOfClass:[BVWorkoutDetailNormalTableViewCell class]]) {
        BVWorkoutDetailNormalTableViewCell *videoCell = (BVWorkoutDetailNormalTableViewCell *)cell;
        [videoCell.firstImageView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj == [BVVideoPlayView sharedInstance]) {
                [[BVVideoPlayView sharedInstance] removeFromSuperview];
                [BVVideoPlayView sharedInstance].url = nil;
            }
        }];
        [videoCell.secondImageView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj == [BVVideoPlayView sharedInstance]) {
                [[BVVideoPlayView sharedInstance] removeFromSuperview];
                [BVVideoPlayView sharedInstance].url = nil;
            }
        }];
        
    }
}

- (BVHomeLocationView *)locationView {
    if (!_locationView) {
        _locationView = [[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE] loadNibNamed:@"BVHomeLocationView" owner:nil options:nil].firstObject;
        [_locationView configWithLocation:self.workoutModel];
        _locationView.height = 55;
    }
    return _locationView;
}


@end
